package cn.zdq.picture_lib.adapter

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.graphics.BlendModeColorFilterCompat
import androidx.core.graphics.BlendModeCompat
import androidx.recyclerview.widget.RecyclerView
import cn.zdq.picture_lib.R
import cn.zdq.picture_lib.activity.PicturePreviewActivity
import cn.zdq.picture_lib.config.PictureConfig
import cn.zdq.picture_lib.config.PictureMimeType
import cn.zdq.picture_lib.config.PictureSelectionConfig
import cn.zdq.picture_lib.listener.OnPhotoSelectChangedListener
import cn.zdq.picture_lib.model.LocalMedia
import cn.zdq.picture_lib.myselfview.dailog.PictureCustomDialog
import cn.zdq.picture_lib.utils.AnimUtils
import cn.zdq.picture_lib.utils.StringUtils
import cn.zdq.picture_lib.utils.ToastUtils
import com.bumptech.glide.Glide
import java.io.File
import java.util.*
import kotlin.collections.ArrayList

/**

 * @Description:
 * @Author: zhoudequn
 * @CreateDate: 2021/8/11 10:05
 */
class PictureImageGridAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private lateinit var mContext: Context

    private lateinit var mData: ArrayList<LocalMedia>

    private lateinit var config: PictureSelectionConfig

    private var imageSelectChangedListener: OnPhotoSelectChangedListener<LocalMedia>? = null

    /**
     * 被选中的数据
     */
    private var selectData: List<LocalMedia> = arrayListOf()

    constructor(context: Context, data: ArrayList<LocalMedia>, configP: PictureSelectionConfig) {
        mContext = context
        mData = data
        config = configP
    }

    override fun getItemViewType(position: Int): Int {
        return if (position == 0) {
            PictureConfig.TYPE_CAMERA
        } else {
            PictureConfig.TYPE_PICTURE
        }
    }

    /**
     * 全量刷新
     *
     * @param data
     */
    fun bindData(data: ArrayList<LocalMedia>) {
        mData = data
        notifyDataSetChanged()
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        if (viewType == PictureConfig.TYPE_CAMERA) {
            val view: View =
                LayoutInflater.from(mContext).inflate(R.layout.picture_item_camera, parent, false)
            return CameraViewHolder(view)
        } else {
            val view: View = LayoutInflater.from(mContext)
                .inflate(R.layout.picture_image_grid_item, parent, false)
            return ViewHolder(view)
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (getItemViewType(position) == PictureConfig.TYPE_CAMERA) {
            val headerHolder = holder as CameraViewHolder
            headerHolder.itemView.setOnClickListener { v: View? ->

            }
        } else {
            val contentHolder = holder as ViewHolder
            val image: LocalMedia = mData.get(position - 1)
            val mimeType = image.mimeType
            contentHolder.ivPicture.setOnClickListener {
                jumpPreviewActivity()
            }
            Glide.with(mContext).load(image.path).into(contentHolder.ivPicture)

            if (config.isSingleDirectReturn) {
                contentHolder.tvCheck.visibility = View.GONE
                contentHolder.btnCheck.visibility = View.GONE
            } else {
                selectImage(contentHolder, isSelected(image))
                contentHolder.tvCheck.visibility = View.VISIBLE
                contentHolder.btnCheck.visibility = View.VISIBLE
                // 启用了蒙层效果
                if (config.isMaxSelectEnabledMask) {
//                    dispatchHandleMask(contentHolder, image)
                }
            }

            if (config.enablePreview || config.enPreviewVideo || config.enablePreviewAudio) {
                contentHolder.btnCheck.setOnClickListener { v: View? ->
                    if (config.isMaxSelectEnabledMask) {
                        if (config.isWithVideoImage) {
                            val selectedCount: Int = getSelectedSize()
                            var videoSize = 0
                            for (i in 0 until selectedCount) {
                                val media: LocalMedia = selectData.get(i)
                                if (PictureMimeType.isHasVideo(media.mimeType)) {
                                    videoSize++
                                }
                            }
                            val errorMsg: String
                            val isNotOption: Boolean
                            if (PictureMimeType.isHasVideo(image.mimeType)) {
                                isNotOption =
                                    !contentHolder.tvCheck.isSelected && videoSize >= config.maxVideoSelectNum
                                errorMsg =
                                    StringUtils.getMsg(
                                        mContext,
                                        image.mimeType,
                                        config.maxVideoSelectNum
                                    )
                            } else {
                                isNotOption =
                                    !contentHolder.tvCheck.isSelected && selectedCount >= config.maxSelectNum
                                errorMsg =
                                    StringUtils.getMsg(
                                        mContext,
                                        image.mimeType,
                                        config.maxSelectNum
                                    )
                            }
                            if (isNotOption) {
                                showPromptDialog(errorMsg)
                                return@setOnClickListener
                            }
                        } else {
                            if (!contentHolder.tvCheck.isSelected && getSelectedSize() >= config.maxSelectNum) {
                                val msg: String =
                                    StringUtils.getMsg(
                                        mContext,
                                        image.mimeType,
                                        config.maxSelectNum
                                    )
                                showPromptDialog(msg)
                                return@setOnClickListener
                            }
                        }
                    }
                    // If the original path does not exist or the path does exist but the file does not exist
                    val newPath = image.realPath
                    if (!TextUtils.isEmpty(newPath) && !File(newPath).exists()) {
                        ToastUtils.s(mContext, PictureMimeType.s(mContext, mimeType))
                        return@setOnClickListener
                    }
                    changeCheckboxState(contentHolder, image)
                }
            }

        }
    }

    override fun getItemCount(): Int {
        return mData.size + 1
    }

    class CameraViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var tvCamera: TextView

        init {
            tvCamera = itemView.findViewById(R.id.tvCamera)

        }
    }

    class ViewHolder(var contentView: View) : RecyclerView.ViewHolder(contentView) {
        var ivPicture: ImageView
        var ivEditor: ImageView
        var tvCheck: TextView
        var tvDuration: TextView
        var tvImageMimeType: TextView
        var tvLongChart: TextView
        var btnCheck: View

        init {
            ivPicture = itemView.findViewById(R.id.ivPicture)
            tvCheck = itemView.findViewById(R.id.tvCheck)
            btnCheck = itemView.findViewById(R.id.btnCheck)
            tvDuration = itemView.findViewById(R.id.tv_duration)
            tvImageMimeType = itemView.findViewById(R.id.tv_image_mime_type)
            tvLongChart = itemView.findViewById(R.id.tv_long_chart)
            ivEditor = itemView.findViewById(R.id.ivEditor)
        }
    }


    fun getData(): List<LocalMedia?>? {
        return if (mData == null) ArrayList() else mData
    }

    fun getSelectedData(): List<LocalMedia> {
        return selectData
    }

    private fun getSelectedSize(): Int {
        return selectData.size
    }

    /**
     * Tips
     */
    private fun showPromptDialog(content: String) {
        val dialog = PictureCustomDialog(mContext, R.layout.picture_prompt_dialog)
        val btnOk: TextView = dialog.findViewById(R.id.btnOk)
        val tvContent: TextView = dialog.findViewById(R.id.tv_content)
        tvContent.text = content
        btnOk.setOnClickListener { dialog.dismiss() }
        dialog.show()
    }

    private fun changeCheckboxState(contentHolder: ViewHolder, image: LocalMedia) {
        val isChecked = contentHolder.tvCheck.isSelected
        val count = getSelectedSize()
        if (isChecked) {
            for (i in 0 until count) {
                val media = selectData[i]
                if (media == null || TextUtils.isEmpty(media.path)) {
                    continue
                }
                if (media.path.equals(image.path)
                    || media.id === image.id
                ) {
                    selectData -= media
                    subSelectPosition()
                    AnimUtils.disZoom(contentHolder.ivPicture, config.zoomAnim)
                    break
                }
            }
        } else {
            // The radio
            if (config.selectionMode === PictureConfig.SINGLE) {
//                singleRadioMediaImage()
            }
            selectData += image
            image.num = selectData.size
//            VoiceUtils.getInstance().play()
            AnimUtils.zoom(contentHolder.ivPicture, config.zoomAnim)
            contentHolder.tvCheck.startAnimation(
                AnimationUtils.loadAnimation(
                    mContext,
                    R.anim.picture_anim_modal_in
                )
            )
        }
        val isRefreshAll = false
        if (isRefreshAll) {
            notifyDataSetChanged()
        } else {
            notifyItemChanged(contentHolder.adapterPosition)
        }
        selectImage(contentHolder, isChecked)
        if (imageSelectChangedListener != null) {
            imageSelectChangedListener?.onChange(selectData)
        }
    }

    /**
     * Select the image and animate it
     *
     * @param holder
     * @param isChecked
     */
    fun selectImage(
        holder: PictureImageGridAdapter.ViewHolder,
        isChecked: Boolean
    ) {
        holder.tvCheck.setSelected(isChecked)
        val colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(
            if (isChecked) ContextCompat.getColor(
                mContext,
                R.color.picture_color_80
            ) else ContextCompat.getColor(mContext, R.color.picture_color_20),
            BlendModeCompat.SRC_ATOP
        )
        holder.ivPicture.setColorFilter(colorFilter)
    }


    fun isSelected(image: LocalMedia): Boolean {
        val size = selectData.size
        for (i in 0 until size) {
            val media = selectData[i]
            if (media == null || TextUtils.isEmpty(media.path)) {
                continue
            }
            if (TextUtils.equals(media.path, image.path)
                || media.id === image.id
            ) {
//                setLocalMediaCropInfo(media, image)
                return true
            }
        }
        return false
    }

    /**
     * Update the selection order
     */
    private fun subSelectPosition() {
        if (config.checkNumMode) {
            val size = selectData.size
            for (index in 0 until size) {
                val media = selectData[index]
                media.num = index + 1
                notifyItemChanged(media.position)
            }
        }
    }


    /**
     * Binding listener
     *
     * @param listener
     */
    fun setOnPhotoSelectChangedListener(listener: OnPhotoSelectChangedListener<LocalMedia>) {
        imageSelectChangedListener = listener
    }

    fun jumpPreviewActivity() {
        val intent = Intent()
        intent.setClass(
            mContext,
            PicturePreviewActivity::class.java
        )
        val bundle = Bundle()
        bundle.putParcelableArrayList(PictureConfig.EXTRA_SELECT_LIST, mData)
        intent.putExtras(bundle)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        mContext.startActivity(intent)
    }
}